import Router from "@koa/router";
import path from "path";
import fs from "fs";
import compose from "./compose.js";

const router = new Router();

/**
 * 路由配置
 * @returns {*}
 */
function routers() {
  var mildArr = new Array();
  // var files = findFile(
  //   process.cwd() + path.sep + "server" + path.sep + "controllers"
  // );
  const files = ["../controllers/admin.js", "../controllers/common.js"];

  files.forEach(function (file) {
    import(file).then((router) => {
      mildArr.push(router.default.routes());
      mildArr.push(router.default.allowedMethods());
    });
    //
  });
  return compose(mildArr);
}

/**
 * 匹配指定模式的文件
 * @param pathArr
 * @returns {Array}
 */
function findFile(pathArr) {
  if (typeof pathArr == "string") {
    pathArr = [pathArr];
  }
  var matchFiles = [],
    filePaths = [];
  pathArr.forEach(function (pah, index, pathArr) {
    filePaths = explorer(pah);
    filePaths.forEach(function (file, fileIndex, files) {
      matchFiles.push(file);
    });
  });
  return matchFiles;
}

/**
 * 递归文件路径
 * @param pth
 * @returns {Array}
 */
function explorer(pth) {
  var pathArr = [];
  var files = fs.readdirSync(pth);
  files.forEach(function (file) {
    var nextPath = pth + path.sep + file;
    if (fs.lstatSync(nextPath).isDirectory()) {
      pathArr = pathArr.concat(explorer(nextPath));
    } else {
      pathArr.push(nextPath);
    }
  });
  return pathArr;
}

export default routers;
